import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Card, Button, Spin, Typography, Divider, Table, Space, Collapse, Badge, Tag } from 'antd';
import { ArrowLeftOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { useLanguage } from '../../i18n/I18nProvider';
import { apiService } from '../../services';
import { ProjectInfo, ScannerMore } from '../../../types';
import './ProjectDetail.scss';

const { Title, Paragraph, Text } = Typography;
const { Panel } = Collapse;

const ProjectDetail: React.FC = () => {
  const { t } = useLanguage();
  const { projectPath } = useParams<{ projectPath: string }>();
  const navigate = useNavigate();
  const [project, setProject] = useState<ProjectInfo | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadProjectDetail = async () => {
      if (!projectPath) return;

      try {
        setLoading(true);
        const decodedPath = decodeURIComponent(projectPath);
        const response = await apiService.projects.getDetail(decodedPath);

        // 确保响应是有效的ProjectInfo对象
        if (response && typeof response === 'object') {
          setProject(response as ProjectInfo);
          setError(null);
        } else {
          throw new Error('Invalid project data format');
        }
      } catch (err) {
        const errorMsg = (err instanceof Error) ? err.message : String(err);
        setError(`${t('projects.loadDetailFailed')}: ${errorMsg}`);
        console.error('加载项目详情失败:', err);
      } finally {
        setLoading(false);
      }
    };

    loadProjectDetail();
  }, [projectPath, t]);

  // 处理返回按钮点击
  const handleBack = () => {
    navigate('/projects');
  };

  // 渲染基本信息
  const renderBasicInfo = () => {
    if (!project || !project.basicInfo) return null;

    return (
      <div className="project-basic-info">
        {project.basicInfo.map((item, index) => {
          const key = Object.keys(item)[0];
          const value = item[key];
          if (!value) return null;

          return (
            <div key={index} className="info-item">
              <Text strong>{key}:</Text>
              <Text>{String(value)}</Text>
            </div>
          );
        })}
      </div>
    );
  };

  // 渲染更多信息
  const renderMoreInfo = (more: ScannerMore) => {
    if (!more || !more.type) return null;

    switch (more.type) {
      case 'table':
        if (!more.list || !Array.isArray(more.list) || more.list.length === 0) {
          return <div>没有表格数据</div>;
        }

        // 为每一行添加key
        const dataWithKey = more.list.map((item, index) => ({
          ...item,
          key: `${more.title}-${index}`
        }));

        const columns = Object.keys(more.list[0] || {}).map(key => ({
          title: key,
          dataIndex: key,
          key,
          render: (value: any) => String(value),
        }));

        return (
          <Table
            dataSource={dataWithKey}
            columns={columns}
            size="small"
            bordered
            pagination={false}
          />
        );

      case 'text':
        return <pre className="text-content">{more.content}</pre>;

      case 'markdown':
        return <div className="markdown-content">{more.content}</div>;

      case 'html':
        return <div dangerouslySetInnerHTML={{ __html: more.content || '' }} />;

      case 'json':
        try {
          const json = more.content ? JSON.parse(more.content) : {};
          return <pre className="json-content">{JSON.stringify(json, null, 2)}</pre>;
        } catch (err) {
          return <div className="error">Invalid JSON</div>;
        }

      default:
        return <div>暂不支持的内容类型: {more.type}</div>;
    }
  };

  if (loading) {
    return (
      <div className="project-detail page-container">
        <div className="loading-container">
          <Spin size="large" />
          <p>{t('app.loading')}</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="project-detail page-container">
        <div className="error-container">
          <ExclamationCircleOutlined className="error-icon" />
          <Title level={4}>{t('app.error')}</Title>
          <Paragraph>{error}</Paragraph>
          <Button type="primary" onClick={handleBack}>
            <ArrowLeftOutlined /> {t('app.back')}
          </Button>
        </div>
      </div>
    );
  }

  if (!project) {
    return (
      <div className="project-detail page-container">
        <div className="not-found-container">
          <Title level={4}>{t('projects.notFound')}</Title>
          <Paragraph>{t('projects.notFoundDesc')}</Paragraph>
          <Button type="primary" onClick={handleBack}>
            <ArrowLeftOutlined /> {t('app.back')}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="project-detail page-container">
      <div className="page-header">
        <Space className="mb-16">
          <Button icon={<ArrowLeftOutlined />} onClick={handleBack}>
            {t('app.back')}
          </Button>
          <Title level={2} style={{ margin: 0 }}>
            {project.name}
          </Title>
          {project.icon && (
            <Badge count={project.icon} style={{ backgroundColor: 'var(--color-primary)' }} />
          )}
        </Space>
        <Paragraph type="secondary">
          {project.path}
        </Paragraph>
      </div>

      <Card className="mb-24">
        <Title level={4}>{t('projects.basicInfo')}</Title>
        <Divider />
        {renderBasicInfo()}
      </Card>

      {project.mores && project.mores.length > 0 && (
        <Collapse defaultActiveKey={['0']} className="mb-24">
          {project.mores.map((more, index) => (
            <Panel
              header={
                <Space>
                  {more.icon && <span className="more-icon">{more.icon}</span>}
                  <span>{more.title}</span>
                </Space>
              }
              key={String(index)}
            >
              {renderMoreInfo(more)}
            </Panel>
          ))}
        </Collapse>
      )}
    </div>
  );
};

export default ProjectDetail;
